using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class HealthBar : MonoBehaviour
{
    public RectTransform root;
    public RectTransform maxHealthBar;
    public RectTransform effectBar;
    public RectTransform CurrentHealthBar;
    public TextMeshProUGUI healthText;

    public PlayerController target;

    private float m_Multiple = 0.5f;
    private float m_CurrentHealthLength;
    private float m_EffectDuration = 0.15f;
    private WaitForSeconds m_EffectWait = new WaitForSeconds(0.1f);
    private Coroutine m_EffectCoroutine = null;

    #region Public方法

    #endregion

    #region Private方法
    private void OnMaxHealthChangeListener(float change)
    {
        maxHealthBar.sizeDelta = new Vector2(target.MaxHealth * m_Multiple + 4, maxHealthBar.sizeDelta.y);
    }
    private void OnCurrentHealthChangeListener(float change)
    {
        //更新显示血量
        healthText.text = Mathf.CeilToInt(target.CurrentHealth).ToString();
        m_CurrentHealthLength = target.CurrentHealth * m_Multiple;
        //重设当前血量条的长度
        CurrentHealthBar.sizeDelta = new Vector2(m_CurrentHealthLength, CurrentHealthBar.sizeDelta.y);

        //当特效条比当前血量条短的时候，直接设置特效条和当前血量条一样长
        if (effectBar.sizeDelta.x <= CurrentHealthBar.sizeDelta.x)
        {
            effectBar.sizeDelta = new Vector2(m_CurrentHealthLength, effectBar.sizeDelta.y);
        }
        else if (change < 0)//否则如果玩家是掉血不是回血，那么开启掉血特效
        {
            if (m_EffectCoroutine != null)
            {
                StopCoroutine(m_EffectCoroutine);
            }
            m_EffectCoroutine = StartCoroutine(EffectCoroutine());
        }
    }
    private IEnumerator EffectCoroutine()
    {
        yield return m_EffectWait;
        float endTime = Time.time + m_EffectDuration;
        float lerp = 0;
        Vector2 startSizeDelta = effectBar.sizeDelta;
        Vector2 endSizeDelta = new Vector2(CurrentHealthBar.sizeDelta.x, effectBar.sizeDelta.y);
        Vector2 newSizeDelta = effectBar.sizeDelta;
        while (Time.time < endTime)
        {
            yield return null;
            lerp += Time.deltaTime / m_EffectDuration;
            newSizeDelta.x = Mathf.Lerp(startSizeDelta.x, endSizeDelta.x, lerp);
            effectBar.sizeDelta = newSizeDelta;
        }
    }
    #endregion

    #region Unity方法

    private void Awake()
    {
        OnMaxHealthChangeListener(target.MaxHealth);
        OnCurrentHealthChangeListener(target.CurrentHealth);

        target.OnMaxHealthChange += OnMaxHealthChangeListener;
        target.OnCurrentHealthChange += OnCurrentHealthChangeListener;
    }
    private void Update()
    {
    }


    #endregion
}